#include <time.h>
#include <unistd.h>
#include <assert.h>
#include "Socket.hpp"
#include "Protocol.hpp"

int main()
{
    srand(time(NULL));
    std::cout << "准备连接" << std::endl;
    uint16_t serverport = 8000;
    string serverip = "106.54.46.147";
    struct sockaddr_in server;
    bzero(&server, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = inet_addr(serverip.c_str());
    server.sin_port = htons(serverport);

    const string opers = "+-*/%=^";

    Sock socket;
    socket.Socket();
    bool r = socket.Connect(serverip, serverport);
    if (!r)
        return 1;

    std::cout << "连接成功, 开始发送数据" << std::endl;
    int cnt = 1;
    while (cnt <= 5)
    {
       std::cout << "=============第" << cnt << "次测试...." << "============" << std::endl;
       string package;
       int x = rand() % 100;
       int y = rand() % 100 + 1;
       char op = opers[rand() % opers.size()];

       Request req(x, y, op);
       req.DebugPrint();

       req.Serialize(&package);
       package = Encode(package);
       std::cout << package << std::endl;
       write(socket._sockfd, package.c_str(), package.size());

       char buff[1024];
       int n = read(socket._sockfd, buff, sizeof(buff));

       string inbuff_stream;
       if (n > 0)
       {
           buff[n] = 0;
           inbuff_stream += buff;
           std::cout << inbuff_stream << std::endl;

           string content;
           bool r = Decode(inbuff_stream, &content);
           assert(r);

           Response resp;
           r = resp.Deserialize(content);
           assert(r);

           resp.DebugPrint();
       }

        std::cout << "=======================================" << std::endl;
        sleep(1);
        cnt++;
    }

    socket.Close();
    return 0;

}
